
//
//  RAProductViewController.m
//  RAFSUManagement
//
//  Created by Piccolo on 22/03/2018.
//  Copyright © 2018 Rayonics. All rights reserved.
//

#import "RAProductViewController.h"
#import "RAFSUSimCardModel.h"
#import "RAFSUHardwareModel.h"
#import "RAFSUDetectInfoView.h"
#import "ZJUsefulPickerView.h"
#import "RAAreaModel.h"

static const NSString *kDefaultProvince = @"湖南";
static const NSString *kDefaultCity = @"长沙";

@interface RAProductViewController () <UITableViewDelegate, UITableViewDataSource, RABleServiceControllerDelegate> {
    
    NSMutableArray<RAFSUSDKPeripheral *> *_bleArray;
    RAFSUSDKPeripheral *_currentBle;
    DGActivityIndicatorView *_indicator;
    RAFSUDetectInfoView *_detectInfoView;
    RAFSUSimCardModel *_simCardModel;
    RAFSUHardwareModel *_hardwareInfo;
    RAAreaModel *_areaModel;
//    NSRAOperatorType _operatorType;
    NSString *_fsuDeviceId;
    BOOL _needUpdateBleArray;
    BOOL _didSetFSUTime;
    BOOL _didSendReadFSUDeviceID;
    BOOL _updateDeviceID;
    BOOL _didReadSimCardInfo;
    BOOL _isFirstSetting;
    NSUInteger _reReadSimCardInfoTimes;
    NSUInteger _reReadMacAndVersionTimes;
    UIButton *_saveImageBtn;
    
}

@property (weak, nonatomic) IBOutlet UITableView *bleTableView;
@property (weak, nonatomic) IBOutlet UIView *rectView;
@property (weak, nonatomic) IBOutlet UIImageView *barCodeImageView;
@property (weak, nonatomic) IBOutlet UIImageView *qrCodeImageView;
@property (weak, nonatomic) IBOutlet UILabel *barCodeLabel;
@property (weak, nonatomic) IBOutlet UIView *barCodeBorderView;
@property (weak, nonatomic) IBOutlet UIView *qrCodeBorderView;
- (IBAction)selectAreaBtnOnClick:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *operatorLabel;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;

@end

@implementation RAProductViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationBar];
    [self setupBleTableView];
    [self setupIndicator];
    [self setupDetectInfoView];
    [self setupSaveImageBtn];
    [self setupInitalization];
    [self updateOperator];
    [self addGestureRecognizerToLabels];
    [self showAreaPickerView];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupFSUSDK];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [RABleUtil disconnectBle];
    [self stopScan];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self updateInitializationBeforeConnectBle];
    _currentBle = _bleArray[indexPath.row];
    [RABleUtil stopScanAndInitSDKFromPeripheral:_currentBle];
    [RAUtil setIndicator:_indicator hidden:NO target:self aboveSubView:self.view];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _bleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"peripheral_cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        RAFSUSDKPeripheral *periperal = _bleArray[indexPath.row];
        [self setSelectBleTableViewCell:cell bleName:periperal.peripheralName RSSI:periperal.RSSI];
    }
    return cell;
}

#pragma mark - Utils

- (void)setupInitalization {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _areaLabel.text = @"区域:";
    _rectView.hidden = YES;
    _isFirstSetting = YES;
}

- (void)setupIndicator {
    
    _indicator = [RAUtil newIndicatorWithTarget:self centerPoint:CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 3)];
}
- (void)setupNavigationBar {
    
    self.navigationController.navigationBarHidden = NO;
    [self setupNavigationBarBtn];
}

- (void)addGestureRecognizerToLabels {
    
    UITapGestureRecognizer *areaLabelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAreaPickerView)];
    // if labelView is not set userInteractionEnabled, you must do so
    [_areaLabel setUserInteractionEnabled:YES];
    [_areaLabel addGestureRecognizer:areaLabelGesture];
}

- (void)setupBleTableView {
    
    _bleTableView.delegate = self;
    _bleTableView.dataSource = self;
}

- (void)setupSaveImageBtn {
    
    _saveImageBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _saveImageBtn.frame = CGRectMake(0, 0, 100, 30);
    _saveImageBtn.center = CGPointMake(SCREEN_WIDTH / 2, CGRectGetMidY(_saveImageBtn.frame));
    [_saveImageBtn setTitle:@"保存图片" forState:UIControlStateNormal];
    [_saveImageBtn addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
    _saveImageBtn.enabled = NO;
    _saveImageBtn.hidden = YES;
    [self.view addSubview:_saveImageBtn];
}

- (void)setupFSUSDK {
    
    [RABleServiceController.sharedManager initBleServiceWithDelegate:self];
    _bleArray = [NSMutableArray<RAFSUSDKPeripheral *> new];
}

- (void)startScanBle {
    
    [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
    if (!_areaModel || !_operatorType) {
        [RAUtil showAlertWithMessage:@"请先选择运营商和城市" alertType:NSRAAlertTypeInfo];
    } else {
        if ([RABleUtil bluetoothIsConnected]) {
            [RABleUtil disconnectBle];
            [NSThread sleepForTimeInterval:.2f];
        }
        if (![RABleServiceController.sharedManager isScanning]) {
            [_bleArray removeAllObjects];
        }
        [_bleTableView reloadData];
        [RABleServiceController.sharedManager startScanBle];
        _needUpdateBleArray = YES;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [RABleServiceController.sharedManager startScanBle];
        });
    }
    
}

- (void)disconnectBle {
    
    [RABleUtil disconnectBle];
}

- (void)stopScan {
    
    [_bleArray removeAllObjects];
    [_bleTableView reloadData];
    [RABleServiceController.sharedManager stopScan];
}

- (void)delayReadSimpleFSUDeviceIDAfterSecond:(CGFloat)second {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
        if (!_updateDeviceID && !_didSendReadFSUDeviceID) {
            [RASimpleFSUSDK readFSUDeviceID];
            _didSendReadFSUDeviceID = YES;
        }
    });
}

- (void)setSelectBleTableViewCell:(UITableViewCell *)cell bleName:(NSString *)bleName RSSI:(NSNumber *)RSSI {
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@(%@)", bleName, RSSI];
    cell.textLabel.font = [UIFont systemFontOfSize:10.f];
    cell.selected = YES;
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    cell.separatorInset=UIEdgeInsetsZero;
    cell.clipsToBounds = YES;
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
}

- (void)updateInitializationBeforeConnectBle {
    
    _updateDeviceID = NO;
    _didSendReadFSUDeviceID = NO;
    _didReadSimCardInfo = NO;
    _didSetFSUTime = NO;
    _reReadSimCardInfoTimes = 0;
    _reReadMacAndVersionTimes = 0;
    _saveImageBtn.hidden = NO;
    _saveImageBtn.enabled = NO;
}

- (void)setupFSUConnectedLayoutAndParameter {
    
    [self updateLayoutFromType:NSRAFSUBleOperationTypeDisconnect];
}

- (void)updateLayoutFromType:(NSRAFSUBleOperationType)type {
    
    if (self.navigationItem.rightBarButtonItems.count) {
        UIButton *rightBarButton = self.navigationItem.rightBarButtonItems[0].customView;
        [RAUtil removeBtnTarget:rightBarButton];
        NSString *title = @"";
        SEL action = nil;
        BOOL bleTableViewHidden = YES;
        switch (type) {
            case NSRAFSUBleOperationTypeNone:
                
                break;
    
            case NSRAFSUBleOperationTypeConnect:
                title = [RAUtil getSingleKeyStr:@"TEXT_CONNECT"];
                action = @selector(startScanBle);
                bleTableViewHidden = NO;
                _saveImageBtn.hidden = YES;
                break;
    
            case NSRAFSUBleOperationTypeDisconnect:
                title = [RAUtil getSingleKeyStr:@"TEXT_DISCONNECT"];
                action = @selector(disconnectBle);
                break;
    
            default:
                break;
        }
        _saveImageBtn.enabled = NO;
        _saveImageBtn.hidden = !bleTableViewHidden;
        _detectInfoView.hidden = !bleTableViewHidden;
        [_detectInfoView clean];
        _bleTableView.hidden = bleTableViewHidden;
        [_bleArray removeAllObjects];
        [_bleTableView reloadData];
        [rightBarButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
        [rightBarButton setTitle:title forState:UIControlStateNormal];
        [rightBarButton sizeToFit];
        
    }
}

- (void)setupNavigationBarBtn {
    
    UIButton *connectBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    connectBtn.frame = CGRectMake(0, 0, 40, 20);
    [connectBtn addTarget:self action:@selector(startScanBle) forControlEvents:UIControlEventTouchUpInside];
    [connectBtn setTitle:[RAUtil getSingleKeyStr:@"TEXT_CONNECT"] forState:UIControlStateNormal];
    [connectBtn sizeToFit];
    
    UIButton *barAndQRCodeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    barAndQRCodeBtn.frame = CGRectMake(0, 0, 40, 20);
    [barAndQRCodeBtn addTarget:self action:@selector(barAndQRCodeBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [barAndQRCodeBtn setTitle:[RAUtil getSingleKeyStr:@"二维码"] forState:UIControlStateNormal];
    [barAndQRCodeBtn sizeToFit];
    UIBarButtonItem *connectBtnItem = [[UIBarButtonItem alloc] initWithCustomView:connectBtn];
    UIBarButtonItem *barAndQRCodeBtnItem = [[UIBarButtonItem alloc] initWithCustomView:barAndQRCodeBtn];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:connectBtnItem, barAndQRCodeBtnItem, nil];
}

- (void)setupDetectInfoView {
    
    _detectInfoView = [RAFSUDetectInfoView createViewFromNib];
    [_detectInfoView ra_setWidth:SCREEN_WIDTH];
    _detectInfoView.hidden = YES;
    [self.view addSubview:_detectInfoView];
}

- (void)updateRectView {
    
    NSString *barString = _simCardModel.IMEI;
    NSString *qrString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@", _currentBle.peripheralName, _hardwareInfo.macAddress, _simCardModel.IMEI, _simCardModel.IMSI, [RAUtil logogramFromOperatorType:_operatorType], _areaModel.province, _areaModel.city];
    
    // 生成条形码
    _barCodeImageView.image = [self generateBarCode:barString width:_barCodeImageView.frame.size.width height:_barCodeImageView.frame.size.height];
    NSLog(@"重新加载条形码");
    _barCodeImageView.image = [UIImage imageWithCIImage:[_barCodeImageView.image CIImage] scale:1.0 orientation:UIImageOrientationRight];
    _barCodeLabel.text = [RAUtil formatCode:barString];
    
    // 生成二维码
    _qrCodeImageView.image = [self generateQRCode:qrString width:_qrCodeImageView.frame.size.width height:_qrCodeImageView.frame.size.height];
    NSLog(@"重新加载二维码");
    _qrCodeImageView.image = [UIImage imageWithCIImage:[_qrCodeImageView.image CIImage]];
    
    [_qrCodeBorderView ra_setBorderColor:[UIColor blackColor] width:1.f];
    [_barCodeBorderView ra_setBorderColor:[UIColor blackColor] width:1.f];
    _rectView.hidden = YES;
    [RAUtil showAlertWithMessage:@"成功生成二维码\n点击上方'二维码'按钮查看" alertType:NSRAAlertTypeSuccessful];
}

// 参考文档
// https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html

- (UIImage *)generateQRCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height {
    
    // 生成二维码图片
    CIImage *qrcodeImage;
    NSData *data = [code dataUsingEncoding:NSUTF8StringEncoding];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    qrcodeImage = [filter outputImage];
    
    // 消除模糊
    CGFloat scaleX = width / qrcodeImage.extent.size.width; // extent 返回图片的frame
    CGFloat scaleY = height / qrcodeImage.extent.size.height;
    CIImage *transformedImage = [qrcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
    
    return [UIImage imageWithCIImage:transformedImage];
}

- (UIImage *)generateBarCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height {
    // 生成条形码图片
    CIImage *barcodeImage;
    NSData *data = [code dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
    CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
    
    [filter setValue:data forKey:@"inputMessage"];
    barcodeImage = [filter outputImage];
    
    // 消除模糊
    CGFloat scaleX = width / barcodeImage.extent.size.width; // extent 返回图片的frame
    CGFloat scaleY = height / barcodeImage.extent.size.height;
    CIImage *transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
    
    return [UIImage imageWithCIImage:transformedImage];
}

- (UIImage *)captureView:(UIView *)view {
    
    //hide controls if needed
    //    CGRect rect = [view bounds];
    //    UIGraphicsBeginImageContext(rect.size);
    //    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //http://blog.csdn.net/jingcheng345413/article/details/56671589
    //更清晰!!
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    return img;
}

- (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo {
    if (error) {
        [[[UIAlertView alloc] initWithTitle:@"保存失败" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
        // Do anything needed to handle the error or display it to the user
    } else {
        [[[UIAlertView alloc] initWithTitle:@"保存成功" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
        // .... do anything you want here to handle
        // .... when the image has been saved in the photo album
    }
}

- (void)saveImage {
    
    /*打印调整38mm*/
    UIImage *image = [self captureView:_rectView];
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), NULL);
}

- (void)updateAreaLabel {
    
    _areaLabel.text = [NSString stringWithFormat:@"区域:%@-%@", _areaModel.province, _areaModel.city];
}

- (void)updateOperator {
    
    _operatorLabel.text = [NSString stringWithFormat:@"运营商:%@", [RAUtil stringFromOperatorType:_operatorType]];
}

//- (void)showOperatorPickerView {
//
//    [ZJUsefulPickerView showSingleColPickerWithToolBarText:@"运营商选择" withData:@[@"中国电信", @"中国移动"] withDefaultIndex:_operatorType ? _operatorType - 1 : NSRAOperatorTypeCNTT - 1 withCancelHandler:^{
//        NSLog(@"@652quxiaole -----");
//
//    } withDoneHandler:^(NSInteger selectedIndex, NSString *selectedValue) {
//        NSLog(@"%@---%ld", selectedValue, selectedIndex);
//        _operatorType = (NSRAOperatorType)(selectedIndex + 1);
//        [self updateOperator];
//        if (_isFirstSetting) {
//            [self showAreaPickerView];
//        }
//    }];
//}

- (void)showAreaPickerView {
    
    [ZJUsefulPickerView showCitiesPickerWithToolBarText:@"省市区选择" withDefaultSelectedValues:@[kDefaultProvince, kDefaultCity] withCancelHandler:^{
        if (!_areaModel) {
            [RAUtil showAlertWithMessage:@"必须选择地区" alertType:NSRAAlertTypeError];
            [self showAreaPickerView];
        }
        
    } withDoneHandler:^(NSArray *selectedValues) {
        NSLog(@"%@---", selectedValues);
        _areaModel = [[RAAreaModel alloc] initWithAreaArray:selectedValues];
        [self updateAreaLabel];
        if (_isFirstSetting) {
            [self startScanBle];
            _isFirstSetting = NO;
        }
    }];
}

#pragma mark - RABleServiceControllerDelegate

- (void)scanedPeripheral:(CBPeripheral *)peripheral peripheralName:(NSString *)peripheralName RSSI:(NSNumber *)RSSI {
    
    if (_needUpdateBleArray) {
        [_bleArray removeAllObjects];
        [_bleTableView reloadData];
        [_bleTableView setNeedsLayout];
        _needUpdateBleArray = NO;
    }
    
    RAFSUSDKPeripheral *fsuSDKPeripheral = [[RAFSUSDKPeripheral alloc] initWithPeripheral:peripheral peripheralName:peripheralName RSSI:RSSI];
    if (![RABleUtil bleArray:_bleArray containsPeripheral:fsuSDKPeripheral]) {
        
        BOOL peripheralFilter = NO;
        
        peripheralFilter = IS_SIMPLE_FSU(fsuSDKPeripheral.peripheralName);
        
        if (peripheralFilter) {
            //        if (YES) {
            [_bleArray addObject:fsuSDKPeripheral];
            [_bleTableView reloadData];
        }
    }
}
- (void)currentFSURssi:(NSNumber *)rssi{
    
}

#pragma mark - Simple FSU

- (void)simpleFsuRequestInitSdkResultInfo:(RAFSUSDKResultInfo *)info {
    
    [RASimpleFSUSDK connectBlueTooth:_currentBle.peripheral withSyscode:DEFINE_SYSCODE withRegcode:DEFINE_REGCODE];
}


- (void)simpleFsuRequestConnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSLog(@"@519连接上了");
        [self setupFSUConnectedLayoutAndParameter];
        [self delayReadSimpleFSUDeviceIDAfterSecond:5.f];
    } else {
        NSLog(@"@526失败");
    }
}

- (void)simpleFsuRequestDisconnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    [self updateLayoutFromType:NSRAFSUBleOperationTypeConnect];
//    [RAUtil showAlertWithTitle:@"TEXT_WARNING" message:@"TEXT_BLE_DISCONNECTED" alertType:NSRAAlertTypeInfo];
}

- (void)simpleFsuRequestActiveReport:(RAFSUSDKActiveReportInfo *)fsuActiveReportInfo {
    //    NSLog(@"@113 active report");
    //    重新更新SDK
    //    加入刷新界面
    [self delayReadSimpleFSUDeviceIDAfterSecond:.5f];
    
    //如果不是设置模式,不需要读取sim卡信息和service 信息
    BOOL updateDetectInfo = _didSetFSUTime && _didReadSimCardInfo;
    
    if (updateDetectInfo) {
        [_detectInfoView updateViewFromDetectInfo:fsuActiveReportInfo.fsuDetectInfo deviceID:_fsuDeviceId macAddress:_hardwareInfo.macAddress];
    }
}

- (void)simpleFsuRequestSetOnlineOpenResultInfo:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSLog(@"453开锁成功");
        //        [RAUtil showSuccessAlertWithTitle:[RAUtil getSingleKeyStr:@"TEXT_TIP"] message:[RAUtil getSingleKeyStr:@"TEXT_OPEN_FSU_SUCCESSFUL"] target:self];
    } else {
        NSLog(@"456开锁失败");
        //        [RAUtil showErrorAlertWithTitle:[RAUtil getSingleKeyStr:@"TEXT_TIP"] message:[RAUtil getSingleKeyStr:@"TEXT_OPEN_FSU_FAILED"] target:self];
    }
}

- (void)simpleFsuRequestSetFsuTimeResultInfo:(RAFSUSDKResultInfo *)info {
    
    _didSetFSUTime = YES;
    [RASimpleFSUSDK readFSUSimCardInfo];
}

- (void)simpleFsuRequestReadFSUDeviceID:(RAFSUSDKResultInfo *)info {
    _didSendReadFSUDeviceID = NO;
    NSString *fsuDeviceID = info.detailDic[@"fsu_device_info"];
    if (![RAUtil checkStringExist:fsuDeviceID]) {
        NSLog(@"@497 读取device id 失败");
        [RASimpleFSUSDK readFSUDeviceID];
        _didSendReadFSUDeviceID = YES;
        return;
    }
    _fsuDeviceId = fsuDeviceID;
    _updateDeviceID = YES;
    [RASimpleFSUSDK setFSUTime];
}

- (void)simpleFsuRequestReadSimCardInfo:(RAFSUSDKResultInfo *)info {
    
    NSLog(@"@670 - %d", info.feedBackState);
    _reReadSimCardInfoTimes ++;
    if (_reReadSimCardInfoTimes == 3) {
        //        [RAUtil showErrorAlertWithTitle:[RAUtil getSingleKeyStr:@"TEXT_ERROR"] message:[RAUtil getSingleKeyStr:@"TEXT_FSU_READ_SIM_CARD_INFO_FAILED"] target:self];
        _reReadSimCardInfoTimes = 0;
        _didReadSimCardInfo = YES;
        [RASimpleFSUSDK readFSUMacAndVersionInfo];
        //        if (_fsuViewControllerType != NSRAFSUViewControllerTypeSetting) {
        //            [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
        //        } else {
        //            [RASimpleFSUSDK readFSUMacAndVersionInfo];
        //        }
        
        return;
    }
    if (info.feedBackState) {
        NSDictionary *fsuSimCardInfoDic = info.detailDic;
        _simCardModel = [[RAFSUSimCardModel alloc] initWithFsuSdkSimCardInfoDic:fsuSimCardInfoDic];
        BOOL isNullInfo = ![RAUtil checkStringExist:_simCardModel.IMEI] &&
        ![RAUtil checkStringExist:_simCardModel.IMSI] &&
        ![RAUtil checkStringExist:_simCardModel.SINR] &&
        ![RAUtil checkStringExist:_simCardModel.signalPower] &&
        ![RAUtil checkStringExist:_simCardModel.RSRQ];
        if (!isNullInfo) {
            _didReadSimCardInfo = YES;
            _reReadSimCardInfoTimes = 0;
            [RASimpleFSUSDK readFSUMacAndVersionInfo];
        } else {
            NSLog(@"@254 info 为空,重读中");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                [RASimpleFSUSDK readFSUSimCardInfo];
            });
        }
        
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
            [RASimpleFSUSDK readFSUSimCardInfo];
        });
    }
}

- (void)simpleFsuRequestReadFSUMacAndVerson:(RAFSUSDKResultInfo *)info {
    
    NSLog(@"@720 - %d - rereadtimes: %ld", info.feedBackState, _reReadMacAndVersionTimes);
    _reReadMacAndVersionTimes ++;
    
    if (_reReadMacAndVersionTimes == 3) {
        _reReadMacAndVersionTimes = 0;
        [RAUtil showAlertWithMessage:[RAUtil getSingleKeyStr:@"TEXT_GET_MAC_ADDRESS_FAILED"] alertType:NSRAAlertTypeError];
        [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
        return;
    }
    
    if (info.feedBackState) {
        NSDictionary *macAndVersionDic = info.detailDic;
        _hardwareInfo = [[RAFSUHardwareModel alloc] initWithMacAddress:macAndVersionDic[@"fsu_mac_address"] softVersion:macAndVersionDic[@"fsu_version"]];
        BOOL isNullInfo = ![RAUtil checkStringExist:_hardwareInfo.macAddress] && ![RAUtil checkStringExist:_hardwareInfo.softVersion];
        if (!isNullInfo) {
            _reReadMacAndVersionTimes = 0;
            [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
            [self updateRectView];
//            _rectView.hidden = NO;
//            _detectInfoView.hidden = NO;
            //do here
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                [RASimpleFSUSDK readFSUMacAndVersionInfo];
            });
        }
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
            [RASimpleFSUSDK readFSUMacAndVersionInfo];
        });
    }
}

#pragma mark - Button Function

- (void)barAndQRCodeBtnOnClick:(UIButton *)button {
    if (_bleTableView.hidden) {
        _detectInfoView.hidden =_rectView.hidden;
        _rectView.hidden = !_rectView.hidden;
        _saveImageBtn.enabled = !_rectView.hidden;
        [RAUtil setDownView:_saveImageBtn aboveView:_rectView spacing:INNER_BOUNDS_SPACING];
    } else {
        _detectInfoView.hidden = YES;
        _rectView.hidden = YES;
    }
    
}

- (IBAction)selectAreaBtnOnClick:(id)sender {
    
    [self showAreaPickerView];
}
@end
